<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>小程序首页轮播图</span>
        <el-button style="float: right; padding: 3px 0" type="text" />
      </div>
      <div class="text item">
        <el-form ref="form" :model="form" label-width="80px">
          <el-upload list-type="picture-card" :action="uploadImgUrl" :headers="headers" :multiple="true" :limit="limit"
            :on-success="handleUploadSuccessAppIndex" :before-upload="handleBeforeUpload" :file-list="fileListAppIndex"
            :on-exceed="handleExceed" :on-preview="handlePictureCardPreview" :on-remove="handleRemoveAppIndex">
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body title="查看图片">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { listResources, getResources, delResources, addResources, updateResources } from "@/api/backend/fileResources";
import { getToken } from "@/utils/auth";

export default {
  name: "Resources",
  //上传图片
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 6,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 10,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件资源表格数据
      resourcesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        oldName: null,
        name: null,
        size: null,
        suffix: null,
        path: null,
        fileDataType: null,
        userId: null,
        client: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      findFileListAppIndex: [],
      // 上传照片窗口
      uploadComfirm: false,
      // 照片列表
      uploadImg: [],
      //图片上传
      number: 0,
      uploadIdsAppIndex: [],
      uploadListAppIndex: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/uploadRotograph", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileListAppIndex: [],
      fileIdsAppIndex: [],
    };
  },
  created() {
    this.allTheAreOnRotationAppIndex();
  },
  methods: {
    setUrl(url) {
      return process.env.VUE_APP_BASE_API + url;
    },
    //小程序首页轮播图
    allTheAreOnRotationAppIndex() {
      let data = {
        fileDataType: "appIndex"
      }
      listResources(data).then(response => {
        this.findFileListAppIndex = response.rows;
        console.log(response)
        console.log(111)
        this.fileIdsAppIndex = response.rows;
        for (let i = 0; i < response.total; i++) {
          this.fileListAppIndex.push({ name: response.rows[i].id, url: this.setUrl(response.rows[i].path), response: { id: response.rows[i].id } })
          this.fileIdsAppIndex.push(response.rows[i].id)
        }
        this.uploadIdsAppIndex = this.fileListAppIndex;
      })
    },
    //查询库里的文件信息
    findListResourcesByIds(row) {
      if (row.fileId != null) {
        listResourcesByIds({ FileId: row.fileId }).then(response => {
          this.findFileList = response.rows;
          this.fileIdfileList = response.rows;
          for (let i = 0; i < response.total; i++) {
            this.fileIds.push(response.rows[i].id.toString())
          }
        });
      } else {
        this.findFileList = [];
        this.fileIdfileList = [];
      }
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }
      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.hiddenImg = true;
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功回调
    handleUploadSuccessAppIndex(res, file) {
      if (res.code === 200) {
        // 文件上传成功后回调文件id
        this.uploadListAppIndex.push({ name: res.id, url: res.path });
        let data = {
          id: res.id,
          fileDataType: "appIndex"
        }
        updateResources(data).then(response => {
        })
        this.uploadedSuccessfullyAppIndex();
      } else {
        this.hiddenImg = false;
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemoveAppIndex(file);
        this.uploadedSuccessfullyAppIndex();
      }
    },
    // 删除图片
    handleRemoveAppIndex(file) {
      for (var i = 0; i < this.fileListAppIndex.length; i++) {
        if (file.response.id == this.fileListAppIndex[i].name) {
          this.fileListAppIndex.splice(i, 1);
          break;
        }
      }
      delResources(file.response.id);
    },
    // 上传结束处理
    uploadedSuccessfullyAppIndex() {
      if (this.number > 0 && this.uploadListAppIndex.length === this.number) {
        var data = this.uploadIdsAppIndex.concat(this.uploadListAppIndex);
        this.uploadListAppIndex = [];
        this.number = 0;
        this.uploadIdsAppIndex = JSON.parse(JSON.stringify(data));
        this.$emit("input", this.listToString(this.uploadIdsAppIndex));
        this.$modal.closeLoading();
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      if (file.response.path == undefined) {
        this.dialogImageUrl = file.url;
      } else {
        this.dialogImageUrl = this.setUrl(file.response.path);
      }
      setTimeout(() => {
        this.dialogVisible = true;
      }, 150)
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, "") + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    },
  }
};
</script>

<style>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
  margin-bottom: 20px;
}
</style>
